package com.cuihom.servicezuuldemo.com.cuihom.filter;

import com.google.common.io.CharStreams;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author cuixing
 * @package com.cuihom.servicezuuldemo.com.cuihom.filter
 * @class MyPostFilter
 * @email xing.cui@magicwindow.cn
 * @date 2018/5/30 上午11:56
 * @description
 */

@Component
public class MyPostFilter extends ZuulFilter{

    private static final Logger log = LoggerFactory.getLogger(MyPostFilter.class);

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        try (final InputStream responseDataStream = ctx.getResponseDataStream()) {
            final String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8"));
            log.info(" responseData : {}", responseData);
            ctx.setResponseBody("zuul post change  -> " + responseData);
        } catch (IOException e) {
            log.warn("Error reading body",e);
        }
        return null;
    }
}